import {ref, computed, inject, watch} from 'vue'
import {defineStore} from 'pinia'

declare global {
    interface Window {
        pywebview: {
            api: {
                insert_game_pads: (mode: object, keys: object, key_press_settings: any) => void,
                set_gamepad_mode: (mode: string | object) => void,
                set_gamepad_keys: (keys: any) => void,
                set_timed_key_press_settings: (settings: any) => void  // 添加定时按键设置的API
            }
        },
        debug: (text: string, type: any) => void // 输出信息至控制台
        printToTerm: (msg: string, level?: 'info' | 'error' | 'warn' | 'command' | 'debug' | 'success') => void // 输出信息至终端
        setTaskBar: (text: string, progress?: number) => void // 输出信息至任务栏
    }
}

// 定义TypeScript接口
export interface ExecutionMethod {
    action: string;
    target: string;
}

export interface ExpectedResult {
    conditionType: string;
    value: string;
    region?: string; // 可选的区域限定参数
}

export interface NextStepCondition {
    conditionType: string;
    value: string;
    nextStep: string;
    region?: string; // 可选的区域限定参数
}

// 定义失败处理接口
export interface FailureHandling {
    action: string;
    value?: string;
}

export interface Step {
    id: string;
    name: string;
    executionCondition: ExpectedResult | null; // 支持ExpectedResult对象、null
    executionMethods: ExecutionMethod[];
    expectedResult: ExpectedResult;
    failureHandling: FailureHandling;
    nextStepConditions: NextStepCondition[];
}

export interface Task {
    name: string;
    count: []; // 作为任务中计数器，一个任务中可以有多个计数器，该数组的长度就是计数器的数量
    timer: []; // 任务中的计时器，一个任务中可以有多个计时器，该数组的长度就是计时器的数量
    steps: Step[];
}

export interface Settings {
    dm: {
        注册码: string;
        附加码: string;
    };
    WebDM: {
        port: number;
        path: string;
    };
    game: {
        名称: string;
        账号: string;
        密码: string;
        path: string;
    };
    tasks: Task[];
    currentTaskIndex: number;
    gamepad: {
        keys: any,
        mode: any
    }

}

export const useProjectStore = defineStore('project', () => {
    const printToTerm = (msg: string, lvl?: 'info' | 'error' | 'warn' | 'command' | 'debug') => {
        window.printToTerm(msg, lvl) // 调用pywebview.api.printToTerm()
    }
    const currentTaskIndex = ref(0)
    const isTaskRunning = ref(false) // 添加任务运行状态


    watch(currentTaskIndex, (newIndex) => {
        settings.value.currentTaskIndex = newIndex
    })

    const setTaskBar = (msg: string, progress?: number) => {
        window.setTaskBar(msg, progress)
    }
    // 定义settings对象，本来可以设置初始值为null，但是Settings类型不允许，这里给一个满足Settings类型的空初始值
    // settings的默认值在loadSettings()方法中指定
    const settings = ref<Settings>({
        dm: {
            注册码: '',
            附加码: ''
        },
        WebDM: {
            port: 8765,
            path: ''
        },
        game: {
            名称: '',
            账号: '',
            密码: '',
            path: ''
        },
        tasks: [],
        currentTaskIndex: 0,
        gamepad: {
            keys: {},
            mode: {}
        }
    })

    const updateSettingsField = (path: string[], value: any) => {
        let current: any = settings.value
        for (let i = 0; i < path.length - 1; i++) {
            current = current[path[i]]
        }
        current[path[path.length - 1]] = value
    }


    // 加载设置
    const loadSettings = async () => {
        try {
            console.log('加载项目配置')
            // @ts-ignore
            let loadedSettings = await window.pywebview.api.loadProjectSettings() || {}
            console.log('加载项目配置成功', loadedSettings)
            // 检查必填项是否为空，增加对settings对象的安全检查
            if (!loadedSettings || typeof loadedSettings !== 'object') {
                printToTerm('配置信息格式错误，请检查后重试！')
                alert('配置信息格式错误，请检查后重试！')
                return
            }
            if (!loadedSettings.dm) { // 确保客户端没有settings.project.toml文件时，配置有初始化值
                loadedSettings.dm = {
                    注册码: '',
                    附加码: ''
                }
            }
            if (!loadedSettings.WebDM) {
                loadedSettings.WebDM = {
                    port: 8765,
                    path: ''
                }
            }
            if (!loadedSettings.game) {
                loadedSettings.game = {
                    名称: '',
                    账号: '',
                    密码: '',
                    path: ''
                }
            }
            // 确保tasks数组存在
            if (!loadedSettings.tasks || !Array.isArray(loadedSettings.tasks)) {
                loadedSettings.tasks = [
                    {
                        name: '新任务',
                        count: [],
                        timer: [],
                        steps: [
                            {
                                name: '示例步骤1',
                                executionCondition: null,
                                executionMethods: [{
                                    action: 'left_click',
                                    target: ''
                                }],
                                expectedResult: {
                                    conditionType: 'none',
                                    value: ''
                                },
                                failureHandling: {
                                    action: 'wait_and_retry',
                                    value: '1'
                                },
                                nextStepConditions: []
                            }
                        ]
                    }
                ]

            }

            if (!loadedSettings.gamepad) {
                loadedSettings.gamepad = {
                    keys: {
                        // 手柄左摇杆的上下左右
                        LJoy_up: ['W'],
                        LJoy_left: ['A'],
                        LJoy_down: ['S'],
                        LJoy_right: ['D'],
                        // 右摇杆的上下左右
                        RJoy_up: ['7'],
                        RJoy_left: ['8'],
                        RJoy_down: ['9'],
                        RJoy_right: ['0'],
                        // 手柄方向键的上左下右
                        keyUp: ['↑'],
                        keyLeft: ['←', '1'],
                        keyDown: ['↓'],
                        keyRight: ['→', '2'],

                        // ABXY 按键
                        a: ['F'],
                        b: ['Space'],
                        x: ['X'],
                        y: ['Y', 'R'],

                        // 肩键
                        lb: ['Q'],
                        rb: ['E'],

                        // 触发键，扳机键
                        lt: ['LCtrl'],
                        rt: ['鼠标右键'], // 右键

                        // 特殊按键
                        back: ['Z', 'B'],
                        start: ['C']
                    },
                    mode: {
                        p1: 'F1',
                        p2: 'F2',
                        sync: 'F3',
                        keyboard: 'F4'
                    },
                    timedKeyPress: {
                        interval: 200,
                        targetKey: "rt",
                        hotkey: "F7",
                        scope: "global"
                    }
                }
            }

            settings.value = loadedSettings
            // 确保currentTaskIndex有效
            if (loadedSettings.currentTaskIndex === undefined ||
                loadedSettings.currentTaskIndex < 0 ||
                loadedSettings.currentTaskIndex >= loadedSettings.tasks.length) {
                loadedSettings.currentTaskIndex = 0
            }
            setTaskBar('加载成功！')
        } catch (error) {
            console.log('加载失败')
            setTaskBar('加载失败！')
        }
    }

    // 保存设置
    const saveSettings = async () => {
        try {
            // @ts-ignore
            const success = await window.pywebview.api.saveProjectSettings(settings.value)
            if (success) {
                setTaskBar('保存成功！')
            } else {
                setTaskBar('保存失败！')
            }
        } catch (error) {
            console.error('保存失败:', error)
            setTaskBar('保存失败！')
        }
    }

    // 任务相关操作函数
    const addTask = (task: Task) => {
        // 检查任务名称是否已存在
        const taskExists = settings.value.tasks.some(t => t.name === task.name)
        if (taskExists) {
            printToTerm(`任务名称 "${task.name}" 已存在，请使用不同的名称！`)
            return false
        }
        settings.value.tasks.push(task)
        return true
    }

    // 更新任务名称
    const updateTaskName = (oldName: string, newName: string) => {
        // 检查新名称是否已存在
        if (oldName !== newName) {
            const taskExists = settings.value.tasks.some(t => t.name === newName)
            if (taskExists) {
                printToTerm(`任务名称 "${newName}" 已存在，请使用不同的名称！`)
                return false
            }
        }

        const task = getTask(oldName)
        if (!task) {
            printToTerm(`未找到任务 "${oldName}"`)
            return false
        }

        task.name = newName
        return true
    }

    const deleteTask = (taskName: string) => {
        if (settings.value.tasks.length <= 1) {
            printToTerm('至少需要保留一个任务！')
            return false
        }
        const index = settings.value.tasks.findIndex(t => t.name === taskName)
        if (index !== -1) {
            settings.value.tasks.splice(index, 1)
            return true
        }
        return false
    }

    // 更新任务的所有步骤
    const updateTaskSteps = (taskName: string, newSteps: Step[]) => {
        const taskIndex = settings.value.tasks.findIndex(task => task.name === taskName)
        if (taskIndex !== -1) {
            // 替换整个 steps 数组以确保响应式更新
            settings.value.tasks[taskIndex].steps = [...newSteps]
        }
    }
    const generateUniqueId = () => {
        return Date.now() + '-' + Math.random().toString(36).substr(2, 9)
    }

    const updateTask = (oldName: string, task: Task) => {
        // 如果名称改变，检查新名称是否已存在
        if (oldName !== task.name) {
            const taskExists = settings.value.tasks.some(t => t.name === task.name)
            if (taskExists) {
                printToTerm(`任务名称 "${task.name}" 已存在，请使用不同的名称！`)
                return false
            }
        }

        const index = settings.value.tasks.findIndex(t => t.name === oldName)
        if (index !== -1) {
            settings.value.tasks[index] = task
            return true
        }
        return false
    }

    const getTask = (taskName: string) => {
        return settings.value.tasks.find(t => t.name === taskName)
    }

    const getTaskNames = () => {
        return settings.value.tasks.map(t => t.name)
    }

    const addStep = (taskName: string, index: number) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return
        }

        const newStep: Step = {
            id: generateUniqueId(),
            name: `新步骤${index + 2}`,
            executionCondition: null,
            executionMethods: [{
                action: 'left_click',
                target: ''
            }],
            expectedResult: {
                conditionType: 'none',
                value: ''
            },
            failureHandling: {
                action: 'wait_and_retry',
                value: '1'
            },
            nextStepConditions: []
        }

        task.steps.splice(index + 1, 0, newStep)
    }

    const deleteStep = (taskName: string, index: number) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return
        }

        if (task.steps.length > 1) {
            task.steps.splice(index, 1)
        } else {
            printToTerm('至少需要保留一个步骤！')
        }
    }

    const updateStep = (taskName: string, index: number, step: Step) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return
        }

        task.steps[index] = step
    }

    const setTasks = (tasks: Task[]) => {
        // 检查任务名称是否唯一
        const taskNames = tasks.map(t => t.name)
        const uniqueNames = new Set(taskNames)
        if (taskNames.length !== uniqueNames.size) {
            printToTerm('任务名称必须唯一！')
            return
        }

        settings.value.tasks = tasks
    }

    // 更新执行条件
    const updateExecutionCondition = (taskName: string, stepIndex: number, condition: ExpectedResult | null) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return false
        }

        if (stepIndex < 0 || stepIndex >= task.steps.length) {
            printToTerm(`步骤索引 "${stepIndex}" 无效`)
            return false
        }

        // 使用展开运算符创建新的步骤对象以确保响应式更新，否则CreateTask.vue中绑定的currentTask不更新，会导致前端画面不更新
        const updatedSteps = [...task.steps]
        updatedSteps[stepIndex] = {
            ...updatedSteps[stepIndex],
            executionCondition: condition
        }
        task.steps = updatedSteps

        return true
    }

    // 更新预期结果
    const updateExpectedResult = (taskName: string, stepIndex: number, condition: ExpectedResult) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return false
        }

        if (stepIndex < 0 || stepIndex >= task.steps.length) {
            printToTerm(`步骤索引 "${stepIndex}" 无效`)
            return false
        }

        task.steps[stepIndex].expectedResult = condition
        return true
    }

    // 添加条件跳转
    const addNextStepCondition = (taskName: string, stepIndex: number) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return false
        }

        if (stepIndex < 0 || stepIndex >= task.steps.length) {
            printToTerm(`步骤索引 "${stepIndex}" 无效`)
            return false
        }

        if (!task.steps[stepIndex].nextStepConditions) {
            task.steps[stepIndex].nextStepConditions = []
        }

        const newCondition: NextStepCondition = {
            conditionType: 'none',
            value: '',
            nextStep: ''
        }

        task.steps[stepIndex].nextStepConditions.push(newCondition)
        return true
    }

    // 更新条件跳转
    const updateNextStepCondition = (taskName: string, stepIndex: number, conditionIndex: number, condition: NextStepCondition) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return false
        }

        if (stepIndex < 0 || stepIndex >= task.steps.length) {
            printToTerm(`步骤索引 "${stepIndex}" 无效`)
            return false
        }

        if (!task.steps[stepIndex].nextStepConditions ||
            conditionIndex < 0 ||
            conditionIndex >= task.steps[stepIndex].nextStepConditions.length) {
            printToTerm(`条件索引 "${conditionIndex}" 无效`)
            return false
        }

        task.steps[stepIndex].nextStepConditions[conditionIndex] = condition
        return true
    }

    // 删除条件跳转
    const deleteNextStepCondition = (taskName: string, stepIndex: number, conditionIndex: number) => {
        const task = getTask(taskName)
        if (!task) {
            printToTerm(`未找到任务 "${taskName}"`)
            return false
        }

        if (stepIndex < 0 || stepIndex >= task.steps.length) {
            printToTerm(`步骤索引 "${stepIndex}" 无效`)
            return false
        }

        if (!task.steps[stepIndex].nextStepConditions ||
            conditionIndex < 0 ||
            conditionIndex >= task.steps[stepIndex].nextStepConditions.length) {
            printToTerm(`条件索引 "${conditionIndex}" 无效`)
            return false
        }

        task.steps[stepIndex].nextStepConditions.splice(conditionIndex, 1)
        return true
    }

    return {
        settings,
        // setSettings,
        updateSettingsField,
        loadSettings,
        saveSettings,
        addTask,
        deleteTask,
        updateTask,
        updateTaskName,
        getTask,
        getTaskNames,
        addStep,
        deleteStep,
        updateStep,
        setTasks,
        updateExecutionCondition,
        updateExpectedResult: updateExpectedResult,
        addNextStepCondition,
        updateNextStepCondition,
        deleteNextStepCondition,
        currentTaskIndex,
        updateTaskSteps,
        generateUniqueId,
        isTaskRunning
    }
})
